package net.xdclass.xdvideo.service.impl;

import net.xdclass.xdvideo.config.WechatConfig;
import net.xdclass.xdvideo.domain.User;
import net.xdclass.xdvideo.mapper.UserMapper;
import net.xdclass.xdvideo.service.UserService;
import net.xdclass.xdvideo.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @program: xdvideo
 * @description: 用户业务实现类
 * @author: rZ
 * @create: 2019-10-29 16:41
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private UserMapper userMapper;


    /**
     * 微信回调查找用户
     * @param code
     * @return
     */
    @Override
    public User saveWechatUser(String code) {

        String accessTokenUrl = String.format(WechatConfig.getOpenAccessTokenUrl(),wechatConfig.getOpenAppId(),wechatConfig.getOpenAppsecret(),code);
        //获取access_token
        Map<String, Object> baseMap = HttpUtils.doGet(accessTokenUrl);
        if (baseMap == null || baseMap.isEmpty()){
            return null;
        }
        String accessToken = baseMap.get("access_token").toString();
        String openId = baseMap.get("openid").toString();

        User dbUser = userMapper.findByOpenid(openId);
        if (dbUser != null) {
            return dbUser;
        }

        //获取用户的基本信息
        String userInfoUrl = String.format(WechatConfig.getOpenUserInfoUrl(),accessToken,openId);
        Map<String, Object> baseUserMap = HttpUtils.doGet(userInfoUrl);
        if (baseUserMap == null || baseUserMap.isEmpty()){
            return null;
        }
        String nickname = baseUserMap.get("nickname").toString();
        Double sexTemp = (Double) baseUserMap.get("sex");
        int sex = sexTemp.intValue();
        String province = baseUserMap.get("province").toString();
        String city = baseUserMap.get("city").toString();
        String country = baseUserMap.get("country").toString();
        String headimgurl = baseUserMap.get("headimgurl").toString();
        StringBuilder sb = new StringBuilder(country).append("||").append(province).append("||").append(city);
        String finalAddress = sb.toString();
        try {
            //解决回调中文乱码
            nickname = new String(nickname.getBytes("ISO-8859-1"),"UTF-8");
            finalAddress = new String(finalAddress.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        User user = new User();
        user.setName(nickname);
        user.setHeadImg(headimgurl);
        user.setCity(finalAddress);
        user.setOpenid(openId);
        user.setSex(sex);
        user.setCreateTime(new Date());
        userMapper.save(user);

        return user;
    }
}
